/*
Copyright (c) 2012 the VATSIM Connector project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "widget.h"
#include <XPWidgets.h>
#include <cassert>

std::map<XPWidgetID, XPInnWidget*>& XPInnWidget::widgetsMap()
{
  static std::map<XPWidgetID, XPInnWidget*> m;
  return m;
}

XPInnWidget::XPInnWidget(XPInnWidget& parent, XPWidgetClass wclass, char const* desc)
: m_lockLayout(false),
  m_id(XPCreateWidget(0, 0, 0, 0, 1, desc, 0, parent.getWidgetID(), wclass))
{
  widgetsMap()[m_id] = this;
  XPAddWidgetCallback(m_id, &callbackWrapper);
}

XPInnWidget::XPInnWidget(std::pair<XPInnWidget*, std::pair<XPWidgetClass, char const*> > const& pair)
: m_lockLayout(false),
  m_id(XPCreateWidget(0, 0, 0, 0, 1, pair.second.second, 0, pair.first->getWidgetID(), pair.second.first))
{
  widgetsMap()[m_id] = this;
  XPAddWidgetCallback(m_id, &callbackWrapper);
}

XPInnWidget::XPInnWidget(XPWidgetClass wclass, char const* desc)
: m_lockLayout(false),
  m_id(XPCreateWidget(0, 0, 0, 0, 0, desc, 1, 0, wclass))
{
  widgetsMap()[m_id] = this;
  XPAddWidgetCallback(m_id, &callbackWrapper);
}

XPInnWidget::~XPInnWidget()
{
  widgetsMap().erase(m_id);
  XPDestroyWidget(m_id, 0);
}

XPInnWidget& XPInnWidget::addChild(XPWidgetClass wclass, char const* desc)
{
  m_children.emplace_back(std::make_pair(this, std::make_pair(wclass, desc)));
  return m_children.back();
}

void XPInnWidget::visitChildren(visitor_func const& v)
{
  for (std::list<XPInnWidget>::iterator it = m_children.begin();
       it != m_children.end();
       ++it)
  {
    v(*it);
    it->visitChildren(v);
  }
}

void XPInnWidget::visitChildren(const_visitor_func const& v) const
{
  for (std::list<XPInnWidget>::const_iterator it = m_children.begin();
       it != m_children.end();
       ++it)
  {
    v(*it);
    it->visitChildren(v);
  }
}

void XPInnWidget::setCallback(XPWidgetMessage msg, callback_func const& f)
{
  m_callbacks[msg] = f;
}

int XPInnWidget::callbackWrapper(XPWidgetMessage msg, XPWidgetID id, xpsdk::intptr p1, xpsdk::intptr p2)
{
  std::map<XPWidgetID, XPInnWidget*>::iterator it = widgetsMap().find(id);

  if (it != widgetsMap().end())
  {
    XPInnWidget* w = it->second;

    bool handled = false;
    std::map<XPWidgetMessage, callback_func>::iterator funcIt = w->m_callbacks.find(msg);
    if (funcIt != w->m_callbacks.end())
      handled = funcIt->second(p1, p2);

    if (msg == xpMsg_Reshape)
    {
      return (w->applyLayout() || handled) ? 1 : 0;
    }
    else return handled ? 1 : 0;
  }
  else return 0;
}

bool XPInnWidget::applyLayout()
{
  if (! m_lockLayout)
  {
    m_lockLayout = true;
    visitChildren(std::tr1::mem_fn(&XPInnWidget::layoutVisitor));
    m_lockLayout = false;
    return true;
  }
  else return false;
}

void XPInnWidget::layoutVisitor()
{
  if (m_layout.get()) m_layout->performLayout(*this);
}

void XPInnWidget::show()
{
  applyLayout();
  XPShowWidget(m_id);
}

void XPInnWidget::hide()
{
  XPHideWidget(m_id);
}

bool XPInnWidget::isVisible() const
{
  return XPIsWidgetVisible(m_id);
}

void XPInnWidget::setGeometry(int left, int top, int right, int bottom)
{
  XPSetWidgetGeometry(m_id, left, top, right, bottom);
}

void XPInnWidget::setDescriptor(std::string const& d)
{
  XPSetWidgetDescriptor(m_id, d.c_str());
}

std::string XPInnWidget::getDescriptor() const
{
  static int const size = 1024;
  static char buf[size];
  XPGetWidgetDescriptor(m_id, buf, size);
  buf[size - 1] = 0;
  return buf;
}

void XPInnWidget::setProperty(XPWidgetPropertyID prop, xpsdk::intptr value)
{
  XPSetWidgetProperty(m_id, prop, value);
}

xpsdk::intptr XPInnWidget::getProperty(XPWidgetPropertyID prop)
{
  return XPGetWidgetProperty(m_id, prop, 0);
}

bool isNumerical(XPInnWidget::SizeHint const& sh)
{
  return sh.m_type != XPInnWidget::SizeHint::type_enum;
}

int getInPixels(XPInnWidget::SizeHint const& sh, int parentPixels)
{
  if (isNumerical(sh))
  {
    if (sh.m_type == XPInnWidget::SizeHint::type_float)
      return sh.m_float * parentPixels;
    else
      return sh.m_int;
  }
  else return parentPixels;
}

void XPInnLayoutHorizontal::performLayout(XPInnWidget& parent)
{
  int parentLeft, parentTop, parentRight, parentBottom;
  XPGetWidgetGeometry(parent.getWidgetID(), &parentLeft, &parentTop, &parentRight, &parentBottom);
  int parentWidth = parentRight - parentLeft;
  int parentHeight = parentTop - parentBottom;

  int widthUsedLeft = 0, widthUsedRight = 0, widthUsedCenter = 0;
  int expanders = 0;
  for (XPInnWidget::const_iterator it = parent.begin(); it != parent.end(); ++it)
  {
    XPInnWidget const& widget = *it;

    if (isNumerical(widget.getDesiredWidth()))
    {
      switch (widget.getHAlign())
      {
      default:
      case XPInnWidget::align_left: widthUsedLeft += getInPixels(widget.getDesiredWidth(), parentWidth); break;
      case XPInnWidget::align_right: widthUsedRight += getInPixels(widget.getDesiredWidth(), parentWidth); break;
      case XPInnWidget::align_center: widthUsedCenter += getInPixels(widget.getDesiredWidth(), parentWidth); break;
      }
    }
    else expanders++;
  }

  int cursorLeft = parentLeft;
  int cursorRight = parentRight - widthUsedRight;
  int cursorCenter = (parentLeft + widthUsedLeft + cursorRight - widthUsedCenter) / 2;
  int unusedWidth = parentWidth - widthUsedLeft - widthUsedRight - widthUsedCenter;
  if (unusedWidth < 0) unusedWidth = 0;
  for (XPInnWidget::iterator it = parent.begin(); it != parent.end(); ++it)
  {
    XPInnWidget& widget = *it;

    int width = isNumerical(widget.getDesiredWidth())
      ? getInPixels(widget.getDesiredWidth(), parentWidth)
      : unusedWidth / expanders;
    int height = getInPixels(widget.getDesiredHeight(), parentHeight);

    int top;
    switch (widget.getVAlign())
    {
    default:
    case XPInnWidget::align_top: top = parentTop; break;
    case XPInnWidget::align_middle: top = parentTop - (parentHeight - height) / 2; break;
    case XPInnWidget::align_bottom: top = parentBottom + height; break;
    }

    switch (widget.getHAlign())
    {
    default:
    case XPInnWidget::align_left:
      widget.setGeometry(cursorLeft, top, cursorLeft + width, top - height);
      cursorLeft += width;
      break;
    case XPInnWidget::align_center:
      widget.setGeometry(cursorCenter, top, cursorCenter + width, top - height);
      cursorCenter += width;
      break;
    case XPInnWidget::align_right:
      widget.setGeometry(cursorRight, top, cursorRight + width, top - height);
      cursorRight += width;
      break;
    }
  }
}

void XPInnLayoutVertical::performLayout(XPInnWidget& parent)
{
  int parentLeft, parentTop, parentRight, parentBottom;
  XPGetWidgetGeometry(parent.getWidgetID(), &parentLeft, &parentTop, &parentRight, &parentBottom);
  int parentWidth = parentRight - parentLeft;
  int parentHeight = parentTop - parentBottom;

  int heightUsedTop = 0, heightUsedBtm = 0, heightUsedMid = 0;
  int expanders = 0;
  for (XPInnWidget::const_iterator it = parent.begin(); it != parent.end(); ++it)
  {
    XPInnWidget const& widget = *it;

    if (isNumerical(widget.getDesiredHeight()))
    {
      switch (widget.getVAlign())
      {
      default:
      case XPInnWidget::align_top: heightUsedTop += getInPixels(widget.getDesiredHeight(), parentHeight); break;
      case XPInnWidget::align_bottom: heightUsedBtm += getInPixels(widget.getDesiredHeight(), parentHeight); break;
      case XPInnWidget::align_middle: heightUsedMid += getInPixels(widget.getDesiredHeight(), parentHeight); break;
      }
    }
    else expanders++;
  }

  int cursorTop = parentTop;
  int cursorBtm = parentBottom + heightUsedBtm;
  int cursorMid = (parentTop - heightUsedTop + cursorBtm + heightUsedMid) / 2;
  int unusedHeight = parentHeight - heightUsedTop - heightUsedBtm - heightUsedMid;
  if (unusedHeight < 0) unusedHeight = 0;
  for (XPInnWidget::iterator it = parent.begin(); it != parent.end(); ++it)
  {
    XPInnWidget& widget = *it;

    int height = isNumerical(widget.getDesiredHeight())
      ? getInPixels(widget.getDesiredHeight(), parentHeight)
      : unusedHeight / expanders;
    int width = getInPixels(widget.getDesiredWidth(), parentWidth);

    int left;
    switch (widget.getHAlign())
    {
    default:
    case XPInnWidget::align_left: left = parentLeft; break;
    case XPInnWidget::align_center: left = parentLeft + (parentWidth - width) / 2; break;
    case XPInnWidget::align_right: left = parentRight - width; break;
    }

    switch (widget.getVAlign())
    {
    default:
    case XPInnWidget::align_top:
      widget.setGeometry(left, cursorTop, left + width, cursorTop - height);
      cursorTop -= height;
      break;
    case XPInnWidget::align_middle:
      widget.setGeometry(left, cursorMid, left + width, cursorMid - height);
      cursorMid -= height;
      break;
    case XPInnWidget::align_bottom:
      widget.setGeometry(left, cursorBtm, left + width, cursorBtm - height);
      cursorBtm -= height;
      break;
    }
  }
}

void XPInnLayoutSuperimpose::performLayout(XPInnWidget& parent)
{
  int parentLeft, parentTop, parentRight, parentBottom;
  XPGetWidgetGeometry(parent.getWidgetID(), &parentLeft, &parentTop, &parentRight, &parentBottom);
  int parentWidth = parentRight - parentLeft;
  int parentHeight = parentTop - parentBottom;

  for (XPInnWidget::iterator it = parent.begin(); it != parent.end(); ++it)
  {
    XPInnWidget& widget = *it;
    int width = getInPixels(widget.getDesiredWidth(), parentWidth);
    int height = getInPixels(widget.getDesiredHeight(), parentHeight);

    int left, top;
    switch (widget.getHAlign())
    {
    default:
    case XPInnWidget::align_left: left = parentLeft; break;
    case XPInnWidget::align_right: left = parentRight - width; break;
    case XPInnWidget::align_center: left = (parentLeft + (parentRight - width)) / 2; break;
    }
    switch (widget.getVAlign())
    {
    case XPInnWidget::align_top: top = parentTop; break;
    case XPInnWidget::align_bottom: top = parentBottom + height; break;
    case XPInnWidget::align_middle: top = (parentTop + (parentBottom + height)) / 2; break;
    }

    widget.setGeometry(left, top, left + width, top - height);
  }
}